package com.edu.hre.struts.action.leave;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.edu.hre.common.cache.PassiveDynaCache;
import com.edu.hre.common.entity.HrePageInfo;
import com.edu.hre.common.utils.BeanFinder;
import com.edu.hre.common.utils.CommonUtils;
import com.edu.hre.common.utils.DynamicConfig;
import com.edu.hre.common.utils.RequestUtils;
import com.edu.hre.db.pojo.HreEmployee;
import com.edu.hre.db.pojo.HreLeaveRequest;
import com.edu.hre.db.pojo.HreLeaveType;
import com.edu.hre.db.pojo.HreUser;
import com.edu.hre.db.pojo.HreUserRoleScreen;
import com.edu.hre.db.service.BaseService;
import com.edu.hre.db.utils.Compare;
import com.edu.hre.struts.form.leave.LeaveApproveListForm;
import com.edu.hre.struts.form.leave.LeaveApproveUpdateForm;
import com.edu.hre.struts.form.leave.LeaveRequestListForm;

public class LeaveApproveListAction extends DispatchAction {
	
	private static final Logger logger = Logger.getLogger(LeaveApproveListAction.class);
	private static final BaseService baseService = BeanFinder.getBean(BaseService.BEAN_NAME, BaseService.class);
	private static final PassiveDynaCache passiveDynaCache = BeanFinder.getBean(PassiveDynaCache.BEAN_NAME, PassiveDynaCache.class);
	
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		CommonUtils.println(CommonUtils.getSourceCodeLocation()); 
		LeaveApproveListForm beanForm = (LeaveApproveListForm) form;
		HreUserRoleScreen userRoleScreen = (HreUserRoleScreen) request.getSession().getAttribute(RequestUtils.Attribute.HreUserRoleScreen);
		HreUser user = (HreUser) request.getSession().getAttribute(RequestUtils.Attribute.USER_INFO);
		beanForm.setCanAdd(userRoleScreen.isCanCreate());
		beanForm.setCanDelete(userRoleScreen.isCanDelete());
		int currentPage = RequestUtils.getParameterInt(request, "page", 1);
		int pageSize = CommonUtils.parseInt(DynamicConfig.getConfig(DynamicConfig.PAGE_SIZE), 20);
		String sortBy = RequestUtils.getParameterStr(request, "sort", null);
		if (sortBy != null) { 
			beanForm.setAsc(!beanForm.isAsc());
			CommonUtils.sortCollection(beanForm.getListObjs(), beanForm.isAsc(), sortBy);
			return mapping.findForward("leaveApproveList");
		}
		List <HreLeaveType> listLeaveType = baseService.getPojos(null, -1, null, null, null, 0, 0, HreLeaveType.class);
		HreLeaveType leaveTypeFirst = new HreLeaveType("-- All --", null, null, null);
		leaveTypeFirst.setId(0);
		listLeaveType.add(0, leaveTypeFirst);
		beanForm.setListLeaveType(listLeaveType);
		
		int totalItems = 0;
		List <HreLeaveRequest> listLeaveRequest = null; 
		
		List<String> listColsName = new ArrayList<String>();
		List<Integer> listCompares = new ArrayList<Integer>();
		List<Object> listValues = new ArrayList<Object>();
		
		listColsName.add("supervisorNum");
		listCompares.add(Compare.EQUAL);
		listValues.add(user.getEmpNumber());
		
		if(beanForm.getFromDate() != null){
			listColsName.add("firstLeave");
			listCompares.add(Compare.GREATER_EQUAL);
			listValues.add(beanForm.getFromDate());
		}
		if(beanForm.getToDate() != null){
			listColsName.add("lastLeave");
			listCompares.add(Compare.LESS_EQUAL);
			listValues.add(beanForm.getToDate());
		}
		if(beanForm.getLeaveTypeId() != 0){
			listColsName.add("leaveTypeId");
			listCompares.add(Compare.EQUAL);
			listValues.add(beanForm.getLeaveTypeId());
		}
		String colsName[] = new String[listColsName.size()];
		for(int i = 0; i < listColsName.size(); i++){
			colsName[i] = listColsName.get(i);
		}
		int[] compares = new int[listCompares.size()];
		for(int i = 0; i < listCompares.size(); i++){
			compares[i] = listCompares.get(i);
		}
		Object[] values = new Object[listValues.size()];
		for(int i = 0; i < listValues.size(); i++){
			values[i] = listValues.get(i);
		}
		
		totalItems = baseService.countByColumns(colsName, compares, values, "id", HreLeaveRequest.class);
		listLeaveRequest = baseService.getPojosAnd(colsName, compares, values, new String[]{"dateCreated"}, new Boolean[]{true}, pageSize, pageSize * (currentPage - 1), HreLeaveRequest.class);
		ArrayList<HrePageInfo> allPages = CommonUtils.getDisplayingPages(currentPage, CommonUtils.getTotalPage(totalItems));
		beanForm.setTotalPage(CommonUtils.getTotalPage(totalItems));
		beanForm.setListPages(allPages);
		beanForm.setTotalItems(totalItems);
		
		List <LeaveApproveUpdateForm> listObjs = new ArrayList<LeaveApproveUpdateForm>();
		for(int i = 0; listLeaveRequest != null && i < listLeaveRequest.size(); i++){
			HreLeaveRequest tmp = listLeaveRequest.get(i);
			HreEmployee employee = baseService.getPojo(tmp.getEmpNum(), HreEmployee.class);
			String fullname = CommonUtils.getFullName(employee);
			String userStr = employee.getMainUsername() == null ? "" : employee.getMainUsername();
			LeaveApproveUpdateForm obj = new LeaveApproveUpdateForm(tmp.getId(), tmp.getEmpNum(),fullname, 
					userStr, tmp.getFirstLeave(), tmp.getLastLeave(), tmp.getApproved(), 
					getNameLeaveType(listLeaveType, tmp.getLeaveTypeId()), tmp.getEmpComment(), tmp.getSupComment());
			listObjs.add(obj);
		}
		beanForm.setListObjs(listObjs);
		String key = RequestUtils.Attribute.LEAVE_APPROVAL_NOTIFICATION + user.getEmpNumber();
		passiveDynaCache.setCachedItem(key, PassiveDynaCache.TIMEOUT_3_HOURS, false);
		return mapping.findForward("leaveApproveList");
	}
	
	private String getNameLeaveType(List <HreLeaveType> listObjs, int id){
		for(int i = 0; listObjs != null && i < listObjs.size(); i++){
			HreLeaveType tmp = listObjs.get(i);
			if(id == tmp.getId()){
				return tmp.getName();
			}
		}
		return null;
	}
}
